#include "tetris.h"
#include "ui_tetris.h"
#include<time.h>
#include<QMessageBox>
#include<QDebug>
#include<QPainter>
#include<QKeyEvent>

Tetris::Tetris(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::Tetris)
{
    ui->setupUi(this);
    this->setGeometry(QRect(500,150,520,820));
    //调整窗口尺寸布局；
    resize(AREA_COL*BLOCK_SIZE+MARGIN*4+4*BLOCK_SIZE,AREA_ROW*BLOCK_SIZE+MARGIN*2);
}

Tetris::~Tetris()
{
    delete ui;
}

void Tetris::paintEvent(QPaintEvent* event)
{
    //updata()或程序第一次启动时自动执行，用于画图
    QPainter painter(this);

    //画游戏背景
    //外墙
    painter.setPen(Qt::black);
    painter.setBrush(Qt::blue);
    painter.drawRect(15,35,490,730);
    //内墙
    painter.setPen(Qt::black);
    painter.setBrush(Qt::green);
    painter.drawRect(20,40,480,720);
    //画格子
    painter.setPen(Qt::yellow);
    for(int i=0;i<=24;i++)//画横线
    {
         painter.drawLine(20,i*30+40,500,i*30+40);
    }
    for(int i=0;i<=16;i++)
    {
        painter.drawLine(i*30+20,40,i*30+20,760);
    }

    //绘制下落方块和稳定方块，注意方块边线的边线的颜色是根据setPen来的，默认黑色
    for(int i=0;i<AREA_ROW;i++)
    {
        for(int j=0;j<AREA_COL;j++)
        {
            //绘制活动方块
            if(game_area[i][j]==1)
            {
                painter.setBrush(QBrush(Qt::red,Qt::SolidPattern));
                painter.drawRect(j*BLOCK_SIZE+MARGIN,i*BLOCK_SIZE+MARGIN+20,BLOCK_SIZE,BLOCK_SIZE);
            }
            //绘制稳定方块
            if(game_area[i][j]==2)
            {
                painter.setBrush(QBrush(Qt::black,Qt::SolidPattern));
                painter.drawRect(j*BLOCK_SIZE+MARGIN,i*BLOCK_SIZE+MARGIN+20,BLOCK_SIZE,BLOCK_SIZE);
            }
        }
    }

    //绘制方块预告
    painter.setBrush(QBrush(Qt::blue,Qt::SolidPattern));
    for(int i=0;i<4;i++)
    {
        for(int j=0;j<4;j++)
        {
            if(next_block[i][j]==1)
            {
                painter.drawRect(MARGIN*3+AREA_COL*BLOCK_SIZE,MARGIN+i*BLOCK_SIZE,BLOCK_SIZE,BLOCK_SIZE);
            }
        }
    }
}

//定义图案代码和边界
//田字
int item1[4][4]=
{
    {0,0,0,0},
    {0,1,1,0},
    {0,1,1,0},
    {0,0,0,0}
};
//右L
int item2[4][4]=
{
    {0,1,0,0},
    {0,1,0,0},
    {0,1,1,0},
    {0,0,0,0}
};
//右L
int item3[4][4]=
{
    {0,0,1,0},
    {0,0,1,0},
    {0,1,1,0},
    {0,0,0,0}
};
//右S
int item4[4][4]=
{
    {0,1,0,0},
    {0,1,1,0},
    {0,0,1,0},
    {0,0,0,0}
};
//左S
int item5[4][4]=
{
    {0,0,1,0},
    {0,1,1,0},
    {0,1,0,0},
    {0,0,0,0}
};
//山
int item6[4][4]=
{
    {0,0,0,0},
    {0,0,1,0},
    {0,1,1,1},
    {0,0,0,0}
};
//I
int item7[4][4]=
{
    {0,0,1,0},
    {0,0,1,0},
    {0,0,1,0},
    {0,0,1,0}
};